package com.wdg.template.controller;

import com.wdg.common.annotation.NeedAuth;
import com.wdg.common.userInfo.CurrentUserInfo;
import com.wdg.common.response.ResponseVO;
import com.wdg.template.controller.req.TemplateReq;
import com.wdg.template.controller.vo.UserVO;
import com.wdg.template.convert.TemplateConvert;
import com.wdg.template.service.TemplateServiceI;
import com.wdg.template.service.dto.TemplateDTO;
import com.wdg.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * 用户controller
 */
@RestController
@RequestMapping("/user")
public class TemplateController {

    @Autowired
    private TemplateServiceI templateServiceI;

    @GetMapping("/getUserByPhoneNumber")
    @NeedAuth
    public ResponseVO getUserByPhoneNumber(String phoneNumber) {
        TemplateDTO templateDTO = templateServiceI.getUserByPhoneNumber(CurrentUserInfo.getUserInfo().getPhoneNumber());
        UserVO userVO = TemplateConvert.INS.dto2VO(templateDTO);
        return ResponseVO.success(userVO);
    }

    @PostMapping("/login")
    public ResponseVO login(@RequestBody @Valid TemplateReq req, HttpServletResponse response) {
        TemplateDTO templateDTO = templateServiceI.login(req);//去校验和登录
        if (Objects.nonNull(templateDTO)) {
            //如果登录成功则去创建token
            this.createToken(response, templateDTO);
        }
        return ResponseVO.success(TemplateConvert.INS.dto2VO(templateDTO));
    }

    /**
     * 创建token
     *
     * @param response
     * @param templateDTO
     */
    private void createToken(HttpServletResponse response, TemplateDTO templateDTO) {
        //生成token
        try {
            String token = JWTUtils.createToken(templateDTO.getPhoneNumber());
            response.setHeader(JWTUtils.USER_LOGIN_TOKEN, token);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
